package com.sweet.eventbus;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;


public class EventBus {
  private static final EventBus eventBus = new EventBus();

  private EventBus() {
    if (eventBus != null) {
      throw new RuntimeException("不允许调用");
    }
  }

  private static final ConcurrentHashMap<String, Handler> eventMap = new ConcurrentHashMap<>();

  public static final EventBus instance() {
    return eventBus;
  }

  public <E> void consumer(String address, Handler<EventResult<E>> handler) {
    eventMap.put(address, handler);
  }

  public <E> void send(String address, E msg) {
    final Handler handler = eventMap.get(address);
    CompletableFuture.runAsync(() -> {
      handler.handler(new EventResult<E>(msg));
    });
  }

}
